package com.boang.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.boang.domain.bo.SocialUser;
import com.boang.domain.po.Users;
import com.boang.resp.Result;
import com.boang.service.UsersService;
import com.boang.utils.HttpUtils;
import com.boang.utils.JwtTokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Objects;

/*
  @author: 13813
  @date: 2024/9/9 11:13
*/
@RestController
public class SocialController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @RequestMapping("/oauth2.0/weibo/callback")
    public Result<String> login(@RequestParam("code") String code) throws Exception {
        //获取授权过的Access Token URL
        String accessTokenUrl = "https://api.weibo.com/oauth2/access_token?"
                + "client_id=" + "2378411175"
                + "&client_secret=" + "e1f472c4055672359eda19f24c47cc19"
                + "&grant_type=authorization_code"
                + "&redirect_uri=" + "http://zhanzxyz.com/oauth2.0/weibo/callback"
                + "&code=" + code;
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(accessTokenUrl);
        //发送POST请求
        HttpResponse accessTokenResponse = httpClient.execute(httpPost);
        //判断请求是否成功 200
        if (accessTokenResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
            //获取返回值
            String accessTokenEntity = EntityUtils.toString(accessTokenResponse.getEntity(), StandardCharsets.UTF_8);
            ObjectMapper mapper = new ObjectMapper();
            //JSON 转 对象
            SocialUser socialUser = mapper.readValue(accessTokenEntity, SocialUser.class);

            //根据uid判断用户是否已经登录过
            LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Users::getUid, socialUser.getUid());
            //查询用户
            Users users = usersService.getOne(wrapper);
            if (!Objects.isNull(users)) {//已经注册过，更新
                users.setAccessToken(socialUser.getAccess_token());
                users.setExpiresIn(socialUser.getExpires_in());
                usersService.updateById(users);
            } else {
                //查询当前社交用户的社交账号信息
                HashMap<String, String> showMap = new HashMap<>();
                showMap.put("access_token", socialUser.getAccess_token());
                showMap.put("uid", socialUser.getUid());
                //发送GET请求
                HttpResponse showResponse = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), showMap);
                //判断请求是否成功 200
                if (showResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                    //获取返回值
                    String showTokenEntity = EntityUtils.toString(showResponse.getEntity(), StandardCharsets.UTF_8);
                    //转 JSON
                    JSONObject jsonObject = JSON.parseObject(showTokenEntity);
                    //构建 Users对象
                    Users showUsers = new Users();
                    showUsers.setUsername(jsonObject.getString("name"));
                    showUsers.setUid(socialUser.getUid());
                    //保存Users 对象
                    usersService.save(showUsers);
                }
            }
        }
        return Result.ok(jwtTokenUtils.generateToken("abc"));
    }
}
